const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/jwt');

module.exports = async (ctx, next) => {
  const authHeader = ctx.header.authorization;
  // 兼容两种格式：'Bearer <token>' 或 直接传递token
  const token = authHeader?.startsWith('Bearer ') ? authHeader.split(' ')[1] : authHeader;
  
  if (!token) {
    ctx.status = 401;
    return ctx.body = { message: '未提供令牌' };
  }
  
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    ctx.state.user = decoded;
    await next();
  } catch (err) {
    ctx.status = 401;
    ctx.body = { message: '无效或过期的令牌，也可能是数据库问题' };
  }
};